/**
 * @author rxliuli
 */
const {not} = rx.CombinedPredicate,
    {isFloat} = rx.stringValidator
const notFloat = not(isFloat)
let oldBaseMonitorDevice
const app = (() => {
    return new BaseValidateVue({
        el: '#app',
        data() {
            return {
                activeName:"first",
                tab: 1,
                form: new BaseMonitorDevice({
                    serverInfo: new BaseServerInfo(),
                }),
                baseMonitorDevIpSegList: [],
                houseMap: new Map(),
                ruleList: [
                    new ValidateObject({
                        ruleName: 'checkTransientFloat',
                        validate: this.transientFloatValidate,
                    }),
                    new ValidateObject({
                        ruleName: 'checkTransientMax',
                        validate: this.transientMaxValidate,
                    }),
                    new ValidateObject({
                        ruleName: 'checkSameNetworkSegment',
                        validate: this.transientSameNetworkSegment,
                    }),
                    new ValidateObject({
                        ruleName: 'checkStartLessThanEnd',
                        validate: this.transientStartLessThanEnd,
                    }),
                    new ValidateObject({
                        ruleName: 'checkNoInclude',
                        validate: this.transientNoInclude,
                    }),
                ],
            }
        },
        methods: {
            createValidateList() {
                return this.ruleList;
            },
            // region 基本信息
            async update() {
                this.$validator.validateAll().then(async (res) => {
                    if (res) {
                        if (await ajaxOption({
                            res: baseMonitorDeviceApi.update(this.form),
                            danger: '更新监控设备信息失败',
                            success: '更新监控设备信息成功',
                        })) {
                            oldBaseMonitorDevice = {...this.form}
                        }
                    } else {
                        rxPrompt.dangerMsg("输入存在错误！");
                    }
                })
            },
            reset() {
                this.form = _.cloneDeep(oldBaseMonitorDevice)
            },
            async transientMaxValidate(val, args) {
                const max = en => en.split('.')[0]
                return max(val).length <= 11
            },
            async transientFloatValidate(val, args) {
                return !notFloat(val)
            },
            async transientSameNetworkSegment(val, args){
                let startIp = args[0];
                let endIp = args[1];
                if (!startIp || !endIp){
                    return true;
                }
                return _.isEqual(startIp.split(".",3),endIp.split(".",3));
            },
            async transientStartLessThanEnd(val,args){
                let startIp = args[0];
                let endIp = args[1];
                if (!startIp || !endIp){
                    return true;
                }
                let startIpSplit = startIp.split('.');
                let endIpSplit = endIp.split('.');
                if(startIpSplit.length !== 4 || endIpSplit.length !== 4){
                    return true;
                }
                return Number(startIpSplit[3]) <= Number(endIpSplit[3])
            },
            async transientNoInclude(val,arg){
                let list = this.form.baseMonitorDevIpSegList;
                let index = arg[0];
                if (list == null) return true;
                let currentSplit;
                try{
                    currentSplit = val.split(".");
                }catch (e){
                    return true;
                }
                for (const i in list) {
                    if (index == i) continue;
                    let item = list[i];
                    try{
                        var startSplit = item.startIp.split(".");
                        var endSplit = item.endIp.split(".");
                        if (
                            startSplit[0] === currentSplit[0] && startSplit[1] === currentSplit[1] && startSplit[2] === currentSplit[2] &&
                            endSplit[0] === currentSplit[0] && endSplit[1] === currentSplit[1] && endSplit[2] === currentSplit[2]
                        ){
                            if(Number(startSplit[3]) <= Number(currentSplit[3]) && Number(endSplit[3]) >= Number(currentSplit[3])){
                                return false;
                            }
                        }
                    }catch (e){}
                }
                return true;
            },
            // endregion

            // region 监控配置

            addBaseMonitorDevIpSeg() {
                // this.baseMonitorDevIpSegList = [...this.form.baseMonitorDevIpSegList, new BaseMonitorDevIpSeg()]
                this.form.baseMonitorDevIpSegList.push(new BaseMonitorDevIpSeg({deviceId:this.form.id}))
            },
            deleteBaseMonitorDevIpSeg(monitorDevIpId, i) {
                if (monitorDevIpId) {
                    this.form.baseMonitorDevIpSegList = this.form.baseMonitorDevIpSegList.filter(({id}) => id !== monitorDevIpId)
                } else {
                    this.form.baseMonitorDevIpSegList.splice(i, 1)
                }
            },
            async updateAndIpList() {
                //新增的
                this.form.baseMonitorDevIpSegList.forEach(o=>o.deviceId=this.form.id);
                const group = rx.groupBy(this.form.baseMonitorDevIpSegList, ({id}) => !!id)
                const diff = {left:[],right:[],common:[]}
                let baseList =group.get(true) || [];
                for(let item of oldBaseMonitorDevice.baseMonitorDevIpSegList){
                    var find = baseList.find(o=>o.id == item.id);
                    if (find){
                        if(item.startIp != find.startIp || item.endIp != find.endIp){
                            diff.right.push(find);
                        }else{
                            diff.common.push(find);
                        }
                    }else{
                        diff.left.push(item);
                    }
                }
                this.$validator.validateAll().then(async (res) => {
                    if (res) {
                        if (await ajaxOption({
                            res: baseMonitorDeviceApi.updateAndIpList({
                                ...this.form,
                                addBaseMonitorDevIpSegList: group.get(false),
                                deleteBaseMonitorDevIpSegIdList: diff.left.map(({id}) => id),
                                updateBaseMonitorDevIpSegList: diff.right,
                            }),
                            danger: '修改监控设备失败',
                            success: '修改监控设备成功',
                        })) {
                            await this.initDevice()
                        }
                    } else {
                        rxPrompt.dangerMsg("输入存在错误！");
                    }
                })
            },
            resetAndIpList() {
                this.form = _.cloneDeep(oldBaseMonitorDevice)
            },

            // endregion

            // region 运行情况

            async refreshServerInfo() {
                this.form.serverInfo = (await baseMonitorDeviceApi.refreshServerInfo(this.form.hostName)) || {}
            },

            async closeApp() {
                // TODO 关闭应用，此处暂不实现
            },

            // endregion

            // region 公共 tab
            getTabClass(tab) {
                return this.tab === tab ? 'ho' : ''
            },
            changeActiveTab(tab) {
                this.tab = tab
            },
            getTabShow(tab) {
                return this.tab === tab ? '' : 'hide'
            },
            safeExec(fn) {
                return rx.safeExec(fn)
            },
            async initDevice() {
                const id = forward.getData().id
                oldBaseMonitorDevice = await baseMonitorDeviceApi.getAndIpList(id)
                oldBaseMonitorDevice.serverInfo = oldBaseMonitorDevice.serverInfo || new BaseServerInfo()
                // noinspection JSPrimitiveTypeWrapperUsage
                this.form = _.cloneDeep(oldBaseMonitorDevice);
                this.form.id = _.cloneDeep(id)
            },
            // endregion
        },
        computed: {
            fieldFormatter() {
                return fieldFormatter
            },
        },
        async mounted() {
            this.initDevice()
            this.houseMap = rx.arrayToMap(await baseHouseInfoApi.selectList(), ({id}) => id, ({houseName}) => houseName);
        },
    })
})()